<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('jgToYWY'))
{
	function jgToYWY($jg) {
		$jg = $jg;
		$jr = strlen($jg);
		if($jr<5) { //4位 千位
			echo $jg.'<s>元</s>';
		}else if($jr>=5 && $jr<9) { // 5-8位
			$new_jg = strrev($jg);
			$w = strrev(substr($new_jg,4));
			$y = strrev(substr($new_jg,0,4));
			echo $w.'<s>万</s>'.($y>0? "$y<s>元</s>" :'');
		}else{ //9位以上
			$new_jg = strrev($jg);
			$yi = strrev(substr($new_jg,8));
			$w = strrev(substr($new_jg,4,4));
			$y = strrev(substr($new_jg,0,4));
			echo $yi.'<s>亿</s>'.($w>0? "$w<s>万</s>" : '').($y>0? "$y<s>元</s>":'');
		}
	}
}

if ( ! function_exists('utf8substr'))
{
	function utf8substr($str, $from, $len)
	{
	    return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
	                       '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
	                       '$1',$str);
	}
}
if ( ! function_exists('filterimg'))
{
	function filterimg($string)
	{
	 
	 $content=preg_replace('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', '', $string);
	 return $content;
	}
}
if ( ! function_exists('strdisplay'))
{
	function strdisplay($str, $length = 1)
	{
		$xing = "";
		for($i = 0; $i < $length; $i++){
			$xing .= '*';
		}
		if($str == null || $str == ''){
			return '';
		}
		if($length >= strlen($str)){
			return $str;
		}
		if( preg_match("/^[\x80-\xffa-zA-Z0-9]{3,60}$/", $str) ){
			$len = mb_strlen($str);
			return mb_substr($str, 0, $len-$length, 'utf-8').$xing;	
		}else{
			$len = strlen($str);
			return substr($str, 0, $len-$length).$xing;	
		}
	}
}

if ( ! function_exists('strdisplay_start'))
{
	function strdisplay_start($str, $length = 1)
	{
		$xing = "**";
		if($str == null || $str == ''){
			return '';
		}
		if(!preg_match("/[^\x80-\xff]/",$str)){
			return mb_substr($str, 0, 1, 'utf-8').$xing;	
		}else{
			return substr($str, 0, $length).$xing;	
		}
	}
}


if ( ! function_exists('strdisplay_title'))
{
	function strdisplay_title($str, $length = 1)
	{
		if(!preg_match("/[^\x80-\xff]/",$str)){
			return mb_substr($str, 0, $length, 'utf-8');	
		}else{
			return substr($str, 0, $length);	
		}
	}
}

if( ! function_exists('getSignature')){
	function getSignature($MerNo, $BillNo, $Amount, $ReturnURL, $MD5key){
		$_SESSION['MerNo'] = $MerNo;
	 	$_SESSION['MD5key'] = $MD5key;
		$sign_params  = array(
	        'MerNo'       => $MerNo,
	        'BillNo'       => $BillNo, 
	        'Amount'         => $Amount,   
	        'ReturnURL'       => $ReturnURL
	    );
	  	$sign_str = "";
	  	ksort($sign_params);
	  	foreach ($sign_params as $key => $val) {
	       $sign_str .= sprintf("%s=%s&", $key, $val);                
	    }
	   return strtoupper(md5($sign_str. strtoupper(md5($MD5key))));   
	}
}

if( ! function_exists('getSignatureCallback')){
 function getSignatureCallback($MerNo, $BillNo, $Amount, $Succeed, $MD5key){
			$sign_params  = array(
        	'MerNo'         => $MerNo,
        	'BillNo'        => $BillNo, 
        	'Amount'        => $Amount,   
        	'Succeed'       => $Succeed
    			);
    
			$sign_str = "";
			ksort($sign_params);
			foreach ($sign_params as $key => $val) {              
                
                $sign_str .= sprintf("%s=%s&", $key, $val);
                               
            }
           //print $sign_str;print '<br/><br/><br/>';
  		return strtoupper(md5($sign_str. strtoupper(md5($MD5key))));   


	}  
}	


if ( ! function_exists('paginate_three') )
{
	function paginate_three($url, $page, $tpages, $adjacents, $pattern='/\{p\}/') {
	
		$prevlabel = "&lsaquo; 前一页";
		$nextlabel = "后一页 &rsaquo;";
		
		$out = "";
		
		$_url = array();
		if($pattern){
			$_url = preg_split($pattern, $url);
		}else{
			$_url = $url;
		}
		if(!isset($_url[1])){
			$_url[1] = '';
		}
		
		// previous
		if($page==1) {
			//$out.= "<span>" . $prevlabel . "</span>\n";
		}
		elseif($page==2) {
			$out.= "<a href=\"" . $_url[0].'1'.$_url[1] . "\">" . $prevlabel . "</a>\n";
		}
		else {
			$out.= "<a href=\"" . $_url[0].($page-1).$_url[1] . "\">" . $prevlabel . "</a>\n";
		}
	
		// first
		if($page>($adjacents+1)) {
			$out.= "<a href=\"" . $_url[0].'1'.$_url[1] . "\">1</a>\n";
		}
	
		// interval
		if($page>($adjacents+2)) {
			$out.= "...\n";
		}
	
		// pages
		$pmin = ($page>$adjacents) ? ($page-$adjacents) : 1;
		$pmax = ($page<($tpages-$adjacents)) ? ($page+$adjacents) : $tpages;
		for($i=$pmin; $i<=$pmax; $i++) {
			if($i==$page) {
				
				$out.= "<strong>" . $i . "</strong>\n";
				
			}
			elseif($i==1) {
				$out.= "<a href=\"" . $_url[0].'1'.$_url[1] . "\">" . $i . "</a>\n";
			}
			else {
				$out.= "<a href=\"" . $_url[0].$i.$_url[1] . "\">" . $i . "</a>\n";
			}
		}
	
		// interval
		if($page<($tpages-$adjacents-1)) {
			$out.= "...\n";
		}
	
		// last
		if($page<($tpages-$adjacents)) {
			$out.= "<a href=\"" . $_url[0].$tpages.$_url[1] . "\">" . $tpages . "</a>\n";
		}
	
		// next
		if($page<$tpages) {
			$out.= "<a href=\"" . $_url[0].($page+1).$_url[1] . "\">" . $nextlabel . "</a>\n";
		}
		else {
			$out.= "<span>" . $nextlabel . "</span>\n";
		}
	
	
		return $out;
	}
}

if( ! function_exists('cut_str')){
	function cut_str($sourcestr,$cutlength){
		$returnstr='';
		$i=0;
		$n=0;
		$str_length=strlen($sourcestr);//字符串的字节数
		while (($n<$cutlength) and ($i<=$str_length))
		{
			$temp_str=substr($sourcestr,$i,1);
			$ascnum=Ord($temp_str);//得到字符串中第$i位字符的ascii码
			if ($ascnum>=224) //如果ASCII位高与224，
			{
				$returnstr=$returnstr.substr($sourcestr,$i,3); //根据UTF-8编码规范，将3个连续的字符计为单个字符
				$i=$i+3; //实际Byte计为3
				$n++; //字串长度计1
			}
			elseif ($ascnum>=192) //如果ASCII位高与192，
			{
				$returnstr=$returnstr.substr($sourcestr,$i,2); //根据UTF-8编码规范，将2个连续的字符计为单个字符
				$i=$i+2; //实际Byte计为2
				$n++; //字串长度计1
			}
			elseif ($ascnum>=65 && $ascnum<=90) //如果是大写字母，
			{
				$returnstr=$returnstr.substr($sourcestr,$i,1);
				$i=$i+1; //实际的Byte数仍计1个
				$n++; //但考虑整体美观，大写字母计成一个高位字符
			}
			else //其他情况下，包括小写字母和半角标点符号，
			{
				$returnstr=$returnstr.substr($sourcestr,$i,1);
				$i=$i+1; //实际的Byte数计1个
				$n=$n+0.5; //小写字母和半角标点等与半个高位字符宽...
			}
		}
		if ($str_length>$cutlength){
			$returnstr = $returnstr."...";//超过长度时在尾处加上省略号
		}
		
		return $returnstr;
	}
}

if ( ! function_exists('rand_string'))
{
	function rand_string($ukey="",$len=6,$type='1',$utype='1',$addChars='') {
	    $str ='';
	    switch($type) {
	        case 0:
	            $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.$addChars;
	            break;
	        case 1:
	            $chars= str_repeat('0123456789',3);
	            break;
	        case 2:
	            $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ'.$addChars;
	            break;
	        case 3:
	            $chars='abcdefghijklmnopqrstuvwxyz123456789'.$addChars;
	            break;
	        default :
	            $chars='ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789'.$addChars;
	            break;
	    }
	    if($len>10 ) {
	        $chars= $type==1? str_repeat($chars,$len) : str_repeat($chars,5);
	    }
	    $chars   =   str_shuffle($chars);
	    $str     =   substr($chars,0,$len);
	    return $str;
	}
}
if( ! function_exists('filePath')){
	function filePath($filename,$data="",$path=""){
		$path = APPPATH.$path;
		if($data==""){
			$f = explode("/",$filename);
			$num = count($f);
			if($num>2){
				$fx = $f;
				array_pop($f);
				$pathe = implode("/",$f);
				$re = F($fx[$num-1],'',$pathe."/");
			}else{
				isset($f[1])?$re = F($f[1],'',APPPATH.$f[0]."/"):$re = F($f[0]);
			}
			return $re;
		}else{
			
			if(!empty($path)) $re = F($filename,$data,$path);
			else $re = F($filename,$data);
		}
	}
}

/**
 * 快速文件数据读取和保存 针对简单类型数据 字符串、数组
 * @param string $name 缓存名称
 * @param mixed $value 缓存值
 * @param string $path 缓存路径
 * @return mixed
 */
if( ! function_exists('F')){
	function F($name, $value='', $path=DATA_PATH) {
	    static $_cache  = array();
	    $filename       = $path . $name . '.php';
	 
	    if ('' !== $value) {
	    	
	        if (is_null($value)) {
	        	
	            // 删除缓存
	            return false !== strpos($name,'*')?array_map("unlink", glob($filename)):unlink($filename);
	        } else {
	            // 缓存数据
	            $dir            =   dirname($filename);
	            // 目录不存在则创建
	            if (!is_dir($dir))
	                mkdir($dir,0755,true);
	            $_cache[$name]  =   $value;
	            return file_put_contents($filename, strip_whitespace("<?php\treturn " . var_export($value, true) . ";?>"));
	        }
	    }
	    
	    
	     
	    if (isset($_cache[$name]))
	        return $_cache[$name];
	    // 获取缓存数据
	    if (is_file($filename)) {
	        $value          =   include $filename;
	        $_cache[$name]  =   $value;
	    } else {
	        $value          =   false;
	    }
	    
	    return $value;
	}
}

if( ! function_exists('de_xie')){
	function de_xie($arr){
		$data=array();
		if(is_array($arr)){
			foreach($arr as $key=>$v){
				if(is_array($v)){
					foreach($v as $skey=>$sv){
						if(is_array($sv)){
								
						}else{
							$v[$skey] = stripslashes($sv);
						}
					}
					$data[$key] = $v;
				}else{
					$data[$key] = stripslashes($v);
				}
			}
		}else{
			$data = stripslashes($arr);
		}
		return $data;
	}
}

if( ! function_exists('text')){
	function text($text,$parseBr=false,$nr=false){
	    $text = htmlspecialchars_decode($text);
	    $text	=	safe($text,'text');
	    if(!$parseBr&&$nr){
	        $text	=	str_ireplace(array("\r","\n","\t","&nbsp;"),'',$text);
	        $text	=	htmlspecialchars($text,ENT_QUOTES);
	    }elseif(!$nr){
	        $text	=	htmlspecialchars($text,ENT_QUOTES);
		}else{
	        $text	=	htmlspecialchars($text,ENT_QUOTES);
	        $text	=	nl2br($text);
	    }
	    $text	=	trim($text);
	    return $text;
	}
}


if( ! function_exists('safe')){
	function safe($text,$type='html',$tagsMethod=true,$attrMethod=true,$xssAuto = 1,$tags=array(),$attr=array(),$tagsBlack=array(),$attrBlack=array()){
	
	    //无标签格式
	    $text_tags	=	'';
	
	    //只存在字体样式
	    $font_tags	=	'<i><b><u><s><em><strong><font><big><small><sup><sub><bdo><h1><h2><h3><h4><h5><h6>';
	
	    //标题摘要基本格式
	    $base_tags	=	$font_tags.'<p><br><hr><a><img><map><area><pre><code><q><blockquote><acronym><cite><ins><del><center><strike>';
	
	    //兼容Form格式
	    $form_tags	=	$base_tags.'<form><input><textarea><button><select><optgroup><option><label><fieldset><legend>';
	
	    //内容等允许HTML的格式
	    $html_tags	=	$base_tags.'<ul><ol><li><dl><dd><dt><table><caption><td><th><tr><thead><tbody><tfoot><col><colgroup><div><span><object><embed>';
	
	    //专题等全HTML格式
	    $all_tags	=	$form_tags.$html_tags.'<!DOCTYPE><html><head><title><body><base><basefont><script><noscript><applet><object><param><style><frame><frameset><noframes><iframe>';
	
	    //过滤标签
	    $text	=	strip_tags($text, ${$type.'_tags'} );
	
	        //过滤攻击代码
	        if($type!='all'){
	            //过滤危险的属性，如：过滤on事件lang js
	            while(preg_match('/(<[^><]+) (onclick|onload|unload|onmouseover|onmouseup|onmouseout|onmousedown|onkeydown|onkeypress|onkeyup|onblur|onchange|onfocus|action|background|codebase|dynsrc|lowsrc)([^><]*)/i',$text,$mat)){
	                $text	=	str_ireplace($mat[0],$mat[1].$mat[3],$text);
	            }
	            while(preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i',$text,$mat)){
	                $text	=	str_ireplace($mat[0],$mat[1].$mat[3],$text);
	            }
	        }
	        return $text;
	}
}


/**
 * 去除代码中的空白和注释
 * @param string $content 代码内容
 * @return string
 */
if( ! function_exists('strip_whitespace')){
	function strip_whitespace($content) {
	    $stripStr   = '';
	    //分析php源码
	    $tokens     = token_get_all($content);
	    $last_space = false;
	    for ($i = 0, $j = count($tokens); $i < $j; $i++) {
	        if (is_string($tokens[$i])) {
	            $last_space = false;
	            $stripStr  .= $tokens[$i];
	        } else {
	            switch ($tokens[$i][0]) {
	                //过滤各种PHP注释
	                case T_COMMENT:
	                case T_DOC_COMMENT:
	                    break;
	                //过滤空格
	                case T_WHITESPACE:
	                    if (!$last_space) {
	                        $stripStr  .= ' ';
	                        $last_space = true;
	                    }
	                    break;
	                case T_START_HEREDOC:
	                    $stripStr .= "<<<THINK\n";
	                    break;
	                case T_END_HEREDOC:
	                    $stripStr .= "THINK;\n";
	                    for($k = $i+1; $k < $j; $k++) {
	                        if(is_string($tokens[$k]) && $tokens[$k] == ';') {
	                            $i = $k;
	                            break;
	                        } else if($tokens[$k][0] == T_CLOSE_TAG) {
	                            break;
	                        }
	                    }
	                    break;
	                default:
	                    $last_space = false;
	                    $stripStr  .= $tokens[$i][1];
	            }
	        }
	    }
	    return $stripStr;
	}
}
